package org.ccay.manage.log.service.impl;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.core.exception.ApplicationException;
import org.ccay.core.exception.impl.CommonApplicationException;
import org.ccay.core.log.Audit;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.server.IServerListService;
import org.ccay.core.server.ServerInfoVO;
import org.ccay.core.util.NetSecurityUtil;
import org.ccay.core.util.PathUtil;
import org.ccay.core.util.StreamUtil;
import org.ccay.log.ServerLogVO;
import org.ccay.manage.log.service.IServerLogService;

/**
 * IServerLogService 实现
 * 
 * @author chaowangbang
 * @since 2011-9-8
 */
@Named
public class ServerLogService implements IServerLogService {
	
	private static final ILogger logger = CcayLoggerFactory.getLogger(ServerLogService.class); 
	/**
	 * 服务器列表服务
	 */
	@Inject
	private IServerListService serverManageService;
	
	
	/* (non-Javadoc)
	 * @see org.ccay.log.service.IServerLogService#findLogList(java.lang.String)
	 */
	@Audit(module="Logs Server Log",operation="find logList",message="find serverlog Name is {#serverName}")
	public List<ServerLogVO> findLogList(int serverNameHashcode, String serverName)
			throws ApplicationException {
		// 配置中读取下载日志的路径的keys
		List<ServerLogVO> fileList = new ArrayList<ServerLogVO>();
		serverName = this.findServerName(serverNameHashcode);
		
		//执行安全检查，防止特殊字符
		NetSecurityUtil.checkFileName(serverName);		

		String logPath = PathUtil.getLogPath(serverName);
		File filecheck = new File(logPath);
		//获取日志目录中的文件
		File[] rsfile = filecheck.listFiles();
		if (rsfile == null || rsfile.length == 0) {
			logger.error("Can not find the file in the {0} directory.{1}",logPath,serverName);
			return fileList;
		}
		//排序
		Arrays.sort(rsfile, new Comparator<File>(){ 
		    public int compare(File f1, File f2) 
		    {
		        return Long.valueOf(f2.lastModified()).compareTo(f1.lastModified()); 
		    } 
		}); 
		Set<Integer> set = new HashSet<Integer>();
		boolean existFlag = true;
		int hashcode =0;
		for (int i = 0; i < rsfile.length; i++) {
			if (rsfile[i].isDirectory()) {
				continue;
			}
			ServerLogVO logVO = new ServerLogVO();
			logVO.setLogName(rsfile[i].getName()); 
			hashcode =  rsfile[i].getName().hashCode();
			//判断hashcode是否重复，如果重复则+10，不重复则不变
			existFlag  = set.add(hashcode);
			if(existFlag){//不重复
				logVO.setLogNameHashcode(hashcode);
			}else{//重复
				logVO.setLogNameHashcode(hashcode+10);
			}
			
			logVO.setServerNameHashcode(serverNameHashcode);
			logVO.setServerName(serverName);	
			logVO.setFileModifiedDate(new Date(rsfile[i].lastModified()));
			
			fileList.add(logVO);
		} 
		return fileList;
	} 
	/**
	 * 根据服务的hashcode找到服务名称
	 * @param serverNameHashcode
	 * @return
	 * @throws ApplicationException
	 */ 
	public String findServerName(int serverNameHashcode) throws ApplicationException{
		List<ServerInfoVO> serverInfoList = findServerList();
		String serverName = null;
		/**
		 * 遍历查找
		 */
		for(ServerInfoVO server:serverInfoList){
			if(server.getServerNameHashcode() == serverNameHashcode){
				serverName = server.getServerName();
				break;
			}
		}
		return serverName;
	}
	/* (non-Javadoc)
	 * @see org.ccay.log.service.IServerLogService#findServerList()
	 */
	public List<ServerInfoVO> findServerList() throws ApplicationException {
		List<ServerInfoVO> serverList = serverManageService.findServerList();
		Set<Integer> set = new HashSet<Integer>();
		boolean existFlag = true;
		int hashcode =0;
		for(ServerInfoVO server :serverList){
			hashcode = server.getServerName().hashCode() ;
			existFlag = set.add(hashcode);
			//判断hashcode是否重复，如果重复则+10，不重复则不变
			if(existFlag){//不重复
				server.setServerNameHashcode(hashcode);
			}else{//重复
				server.setServerNameHashcode(hashcode+10);
			}
		}
		return serverList;
	}
	
	/* (non-Javadoc)
	 * @see org.ccay.log.service.IServerLogService#testCreateLog()
	 */
	public void testCreateLog() throws ApplicationException {
		String path= PathUtil.getLogPath("", false);
		
		File f = null;
		FileWriter fw = null;
		try {
				f =new File(path, System.currentTimeMillis() + "_test.log");
				if(!f.createNewFile()){
					throw new CommonApplicationException("Can not create file.");
					}
				 fw = new FileWriter(f);
				 fw.write("Ccay Log Test");
			
		} catch (IOException e) {
			throw new CommonApplicationException(e.getMessage(), e);
		}
		finally{
			StreamUtil.closeStreams(fw);
		}
	}
	/**
	 * 根据服务名称的hashcode和日志文件的hashcode来查找日志文件名
	 * @param serverNameHashcode
	 * @param logNameHashcode
	 * @return
	 * @throws ApplicationException
	 */
	public String findLogFileName(int serverNameHashcode, int logNameHashcode)
			throws ApplicationException {		 
		String logFileName = null;
		List<ServerLogVO> serverLogList= findLogList(serverNameHashcode,"");
		for(ServerLogVO serverLog:serverLogList){
			 if(serverLog.getLogNameHashcode() == logNameHashcode){
				 logFileName =serverLog.getLogName();
				 break;
			 }
		 }
		return logFileName;
	}

}
